package com.example.hutool;

import cn.hutool.core.collection.ListUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class CompletableFutureTest {

    public static void main(String[] args) {
        List<Integer> sourceList = new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            sourceList.add(i);
        }
        System.out.println("sourceList size " + sourceList.size());

        // 要用线程安全的集合
        List<String> dataList = Collections.synchronizedList(new ArrayList<>());
        List<CompletableFuture<Void>> futures = new ArrayList<>();

        List<List<Integer>> lists = ListUtil.splitAvg(sourceList, 3);
        for (List<Integer> subList : lists) {
            futures.add(CompletableFuture.runAsync(() -> {
                for (Integer i : subList) {
                    String str = String.valueOf(i);
                    dataList.add(str);
                }
            }));
        }

        //等待全部完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
//        futures.forEach(CompletableFuture::join);
        System.out.println("dataList size " + dataList.size());

        System.out.println("main thread todo ...");
    }
}
